<?php

namespace app\admin\service;

use app\common\Message;
use app\model\ConsultTimeModel;
use app\model\DepartmentModel;
use app\model\UserModel;
use app\model\UserTagModel;
use PhpOffice\PhpWord\TemplateProcessor;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Service;
use ZipArchive;

class ConsultantExportService extends Service
{
    use Message;

    public function getConsultantIdExport($param){
        //验证身份
        $isCheck = $this->CheckParam($param);
        if(!$isCheck){
            $this->message = $this->getMessage();
            return false;
        }
        //获取要导出的信息
        $list = $this->getConsultantInfo($param);
        if(!$list){
            $this->message = $this->getMessage();
            return false;
        }
        return $this->getResult();
    }

    public function consultantSeniorExport($param)
    {
        //验证身份
        $isCheck = $this->CheckParam($param);
        if(!$isCheck){
            $this->message = $this->getMessage();
            return false;
        }
        //获取要导出的信息
        $list = $this->getConsultantInfo($param);
        if(!$list){
            $this->message = $this->getMessage();
            return false;
        }
        //导出excel
        $UserExportService = new UserExportService($this->app);
        $ret['excel'] = $UserExportService->ConsultExport($this->getResult());
        //导出word
        if(isset($param['statisticType']) && strlen($param['statisticType']>0)){
            $word = $this->ExportConsultWord($this->getResult(),$param);
            if(!$word){
                $this->message = $this->getMessage();
                return false;
            }
            $ret['word'] = $this->getResult();
        }
        $this->result = $ret;
        return true;
    }

    /**
     * 验证参数
     * @param $param
     * @return bool
     */
    public function CheckParam($param): bool
    {
        switch ($param['role_mode']){
            case 0;//超级管理
            case 1;//管理员【只能导出负责的部门】
                break;
            case 2:
            default:
                $this->message = '此账号暂无高级筛选导出权限！';
                return false;
        }
        return true;
    }

    /**
     * 获取咨询师ID集合
     * @param $param
     * @return bool
     */
    public function getConsultantInfo($param): bool
    {
        $where = [];
        if (!empty($param['role_id'])) {
            $where[] = ['role_id', '=', $param['role_id']];
        }
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
        } else {
            if (!empty($param['start_time'])) {
                $where[] = ['time', '>=', $param['start_time']];
            }
            if (!empty($param['end_time'])) {
                $where[] = ['time', '<=', $param['end_time']];
            }
        }
        if (isset($param['is_scheduling']) && strlen($param['is_scheduling']) > 0) {
            $where[] = ['is_scheduling', '=', $param['is_scheduling']];
        }
        $UserModel = new UserModel();
        if (!empty($param['sex'])) {
            //普通用户的性别筛选
            $ids = $UserModel->where('sex', '=', $param['sex'])->column('id');
            if (count($ids)) {
                $where[] = ['id', 'in', $ids];
            } else {
                $where[] = ['id', '=', -1];
            }
        }
        $UserTagModel = new UserTagModel();
        if (!empty($param['tags'])) {
            $uids = $UserTagModel->where('tag_id', 'in', $param['tags'])->column('uid');
            if (count($uids) > 0) {
                $where[] = ['id', 'in', $uids];
            }else{
                $where[] = ['id', '=', -1];
            }
        }
        if (!empty($param['department_id'])) {
            $ConsultTimeModel = new ConsultTimeModel();
            $department_id = $ConsultTimeModel->where('unit_id','=',$param['unit_id'])->column('department_id');
            if (!empty($department_id)) {
                if (!in_array(0, $department_id)) {
                    $where[] = ['department_id', 'in', $department_id];
                }
            }else{
                $where[] = ['id', '=', -1];
            }
        }
        $where[] = ['role_mode', '=', 2];
        $where[] = ['unit_id','=',$param['unit_id']];
        $data = $UserModel->where($where)
            ->with([
                'unitName',
                'userTag' => function ($queue) {
                    $queue->with(['tag']);
                }
            ])
            ->order('id desc')->column('id');
        if(count($data)>0){
            $this->result = $data;
            return true;
        }else{
            $this->message = '暂无数据！';
            return false;
        }
    }

    /**
     * 导出压缩包
     * @param $param //咨询师ID集合
     * @param $tempParam //前端传的参数
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function ExportConsultWord($param, $tempParam): bool
    {
        $zip = new ZipArchive();
        $ext = '.zip';
        $save_name = '/export/packConsultant' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname('./public' . $save_name . $ext);
        folder_build($file_path);
        $zipFileName = $save_name . $ext; // 压缩包文件名
        if ($zip->open('./public' . $zipFileName, ZipArchive::CREATE) !== TRUE){
            $this->message = '无法创建压缩文件';
            return false;
        }
        $file = '/consultant_template_recode/' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        foreach ($param as $k => $item) {
            //获取每个咨询师筛选的详细资料的word的文件
            $nickname  = UserModel::query()->where('id',$item)->value('name');
            $fileName = $file . $nickname.$k. '的咨询统计资料.docx'; //word模板名
            $ok = $this->ConsultantFormation($item,$tempParam,$fileName);//渲染word模板
            if(!$ok){
                $this->message = $this->getMessage();
                return false;
            }
            $zip->addFile('./public' . $fileName, $nickname . '的咨询统计资料'.$k.'.docx');
        }
        $zip->close();
        $this->result = oss('./public' . $save_name . $ext, $ext);
        return true;
    }

    /**
     * 导出word
     * @param $param
     * @param $tempParam
     * @param $fileName
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function ConsultantFormation($param, $tempParam, $fileName): bool
    {
        //获取每个用户的内容
        $info = $this->getConsultantContent($param);
        if(!$info){
            $this->message = $this->getMessage();
            return false;
        }
        $data = $this->getResult();
        /*根据用户的勾选选择不同的模板-开始*/
        $types = 0;
        if (in_array('0', $tempParam['statisticType'])) $types |= 1;
        if (in_array('1', $tempParam['statisticType'])) $types |= 1 << 1;
        if (in_array('2', $tempParam['statisticType'])) $types |= 1 << 2;
        if (in_array('3', $tempParam['statisticType'])) $types |= 1 << 3;
        if (in_array('4', $tempParam['statisticType'])) $types |= 1 << 4;
        if (in_array('5', $tempParam['statisticType'])) $types |= 1 << 5;
        if (in_array('6', $tempParam['statisticType'])) $types |= 1 << 6;
        if (in_array('7', $tempParam['statisticType'])) $types |= 1 << 7;
        switch ($types){
            case 2: //只有1
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount1.docx');
                break;
            case 6: //只有1,2
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount1-2.docx');
                break;
            case 10://只有1,3
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount1-3.docx');
                break;
            case 14: //只有1,2,3
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount.docx');
                break;
            case 4: //只有2
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount2.docx');
                break;
            case 12: //只有2,3
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount2-3.docx');
                break;
            case 8: //只有3
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/user_template/ConsultantCount3.docx');
                break;
            default:
                $this->message = '参数错误！';
                return false;
        }
        /*根据用户的勾选选择不同的模板-结束*/
        $this->getConsultantTemplate($data,$templateProcessor,$tempParam); //渲染模板

        // 保存修改后的文档
        $file_path  = dirname('./public' .$fileName);
        folder_build($file_path);
        $templateProcessor->saveAs('./public' .$fileName);
        return true;
    }

    /**
     * 获取要导出的数据
     * @param $param
     * @return array|true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getConsultantContent($param): bool|array
    {
        $ConsultTimeModel = new ConsultTimeModel();
        $DepartmentModel = new DepartmentModel();
        $where['id'] = $param;
        $data = UserModel::query()->where($where)
            ->with([
                'unitName',
                'userTag' => function ($queue) {
                    $queue->with(['tag']);
                }
            ])
            ->field('id,name,sex,age,unit_id')->find()->toArray();
        //服务对象
        $department_id = $ConsultTimeModel->where([
            ['consult_id','=',$param],
            ['start_time','>',time()]
        ])->distinct(true)->column('department_id');
        if (in_array(0,$department_id)) {
            $ServerType = '所有部门';
            $ServerName = '--';
        }else{
            $ServerType = '服务指定部门';
            $ServerName = $DepartmentModel->where('id','in',$department_id)->column('name');
            $ServerName = implode('、',$ServerName);
        }
        if($ServerType == '所有部门'){
            $ServerName = '所有部门';
        }
        $data['department_name'] = $ServerName;
        $this->result = $data;
        return true;
    }

    /**
     * 渲染模板数据
     * @param $data
     * @param $templateProcessor
     * @param $tempParam  //前端传的参数【只用到图片字段】
     * @return mixed
     */
    public function getConsultantTemplate($data, $templateProcessor, $tempParam): mixed
    {
//        var_dump($tempParam);die;
        //处理图片1
        $img = [];
        foreach($tempParam['img']??[] as $item){
            $img[$item['id']] = $item;
        }

        $img1 = [];
        if(check_array_key('img1',$tempParam)){
            foreach($tempParam['img1']??[] as $item){
                $img1[$item['id']] = $item;
            }
        }
        $img2 = [];
        if(check_array_key('img2',$tempParam)){
            foreach($tempParam['img2']??[] as $item){
                $img2[$item['id']] = $item;
            }
        }
        $sex = $this->getSex($data);
        $templateProcessor->setValue('name', $data['name']); // 姓名
        $templateProcessor->setValue('sex', $sex); // 性别
        $templateProcessor->setValue('age', $data['age']); // 年龄
        $templateProcessor->setValue('unit_name', $data['unit_name']); // 所在单位
        $templateProcessor->setValue('department_name', $data['department_name']); // 所在部门
        /*咨询师标签-开始*/
        foreach($data['userTag'] as $key=>$value){
            $index = $key+1;
            $templateProcessor->setImageValue('tag'.$index, ['path' => './public'.$value['tag_icon'], 'width' => 60, 'height' => 40]);//标签
        }
        $tempCount = count($data['userTag']);
        if($tempCount<10){
            //默认设置每个值都为空
            for ($i=$tempCount+1;$i<=10;$i++){
                $templateProcessor->setValue('tag' . $i, ' ');//标签
            }
        }
        if(count($tempParam['statisticType'])>0){
            if(in_array('1',$tempParam['statisticType'])){
                //接待人数统计图片
                if(!empty($img[$data['id']]['one'])){
                    $templateProcessor->setImageValue('img', ['path' => $img[$data['id']]['one'], 'width' => 500, 'height' => 400]);
                }else{
                    $templateProcessor->setValue('img', ' '); // 接待人数统计图片
                }
            }else{
                $templateProcessor->setValue('img', ' '); // 接待人数统计图片
            }
            if(in_array('2',$tempParam['statisticType'])){
                //问题分类统计图片
                if(!empty($img1[$data['id']]['one'])){
                    $tempImg = $img1[$data['id']]['one'];
                    $templateProcessor->cloneRow('img1', count($tempImg), true, true);
                    foreach($tempImg as $key=>$value){
                        $index = $key+1;
                        $templateProcessor->setImageValue('img1#' . $index, ['path' => $value, 'width' => 500, 'height' => 400]);
                    }
                }else{
                    $templateProcessor->setValue('img1', ' '); // 问题分类统计图片
                }
            }else{
                $templateProcessor->setValue('img1', ' '); // 问题分类统计图片
            }
            if(in_array('3',$tempParam['statisticType'])){
                //月度人数统计图片
                if(!empty($img2[$data['id']]['one'])){
                    $templateProcessor->setImageValue('img2', ['path' => $img2[$data['id']]['one'], 'width' => 500, 'height' => 400]);
                }else{
                    $templateProcessor->setValue('img2', ' '); // 月度人数统计图片
                }
            }else{
                $templateProcessor->setValue('img2', ' '); // 月度人数统计图片
            }
        }else{
            $templateProcessor->setValue('img', ' '); // 接待人数统计图片
            $templateProcessor->setValue('img1', ' '); // 问题分类统计图片
            $templateProcessor->setValue('img2', ' '); // 月度人数统计图片
        }
        return $templateProcessor;
    }

    /**
     * 获取性别
     * @param $data
     * @return string
     */
    private function getSex($data): string
    {
        $sex = match ($data['sex']) {
            0 => '',
            1 => '男',
            default => '女',
        };
        return $sex;
    }
}